package com.walkline.util.ui;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.system.Display;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.TouchEvent;
import net.rim.device.api.ui.XYEdges;

import com.walkline.app.WeiboAppConfig;
import com.walkline.util.BitmapMask;
import com.walkline.util.Function;
import com.walkline.util.GPATools;
import com.walkline.weibo.inf.Comment;
import com.walkline.weibo.inf.Status;
import com.walkline.weibo.inf.User;

public class RepostListStyleButtonField extends Field
{
    public static int DRAWPOSITION_TOP = 0;
    public static int DRAWPOSITION_BOTTOM = 1;
    public static int DRAWPOSITION_MIDDLE = 2;
    public static int DRAWPOSITION_SINGLE = 3;

    private static final int CORNER_RADIUS = 0;

    private static final int HPADDING = Display.getWidth() <= 320 ? 4 : 6;
    private static final int VPADDING = 4;

    private static final int COLOR_BACKGROUND = 0xFFFFFF;
    //private static final int COLOR_BACKGROUND_TITLE = 0xA9A9A9;
    private static final int COLOR_BORDER = 0xBBBBBB;
    //private static final int COLOR_BACKGROUND_FOCUS = 0x186DEF;
    private static final int COLOR_BACKGROUND_FOCUS = 0x054800;//0x0A9000;

    private MyLabelFieldWithNewline _labelContent;
    private MyLabelField _labelTime;

    //private static Font FONT_SCREENNAME = WeiboAppConfig.FONT_SCREENNAME;
	private static Font FONT_TIME = WeiboAppConfig.FONT_TIME;

    private Bitmap _avatarIcon;
    private Bitmap _image_Status;
    private Bitmap _image_Retweet;

    private String _avatar_url = "";
    private byte[] _avatar_data;
    private int _avatar_size = 0;

    private int _rightOffset;
    private int _leftOffset;
    private int _labelHeight;

    private Status _status;
    private Comment _comment;
    private User _user;

    private int _drawPosition = -1;

    public RepostListStyleButtonField(Status status)
    {
        super(USE_ALL_WIDTH | Field.FOCUSABLE);

    	String content = status.getUser().getScreenName() + "：" + status.getText();
    	String time = status.getCreatedAtShort();

    	_avatarIcon = Bitmap.getBitmapResource("avatar.png");
    	_avatar_url = status.getUser().getProfileImageUrl();
    	_avatar_size = _avatarIcon.getWidth();
    	//_id_str = status.getIdStr();
    	_status = status;
    	_user = status.getUser();

        if (content != null) {_labelContent = new MyLabelFieldWithNewline(content);}
        if (time != null) {_labelTime = new MyLabelField(time, 0);}

        setFontSize();
    }

    public RepostListStyleButtonField(Comment comment)
    {
        super(USE_ALL_WIDTH | Field.FOCUSABLE);

    	String content = comment.getUser().getScreenName() + "：" + comment.getText();
    	String time = comment.getCreatedAtShort();

    	_avatarIcon = Bitmap.getBitmapResource("avatar.png");
    	_avatar_url = comment.getUser().getProfileImageUrl();
    	_avatar_size = _avatarIcon.getWidth();
    	_comment = comment;
    	_user = comment.getUser();

        if (content != null) {_labelContent = new MyLabelFieldWithNewline(content);}
        if (time != null) {_labelTime = new MyLabelField(time, 0);}

        setFontSize();
    }        

    public void setFontSize()
    {
    	if (_labelTime != null) {_labelTime.setFont(FONT_TIME);}
    }

    public Status getStatus() {return _status;}

    public Comment getComment() {return _comment;}

    public User getUser() {return _user;}

    public byte[] getAvatarData() {return _avatar_data;}

    public String getAvatarUrl() {return _avatar_url;}

    public void setAvatarData(byte[] data)
    {
    	_avatar_data = data;

		if (_avatar_data != null)
		{
			Bitmap newIcon = Bitmap.createBitmapFromBytes(_avatar_data, 0, -1, 1);

			_avatar_size = newIcon.getWidth();
			newIcon = GPATools.ResizeTransparentBitmap(newIcon, _avatar_size, _avatar_size, Bitmap.FILTER_LANCZOS, Bitmap.SCALE_STRETCH);

			BitmapMask mask = new BitmapMask(new XYEdges(5, 5, 5, 5), Bitmap.getBitmapResource("mask.png"));
			mask.applyMask(newIcon);

			_avatarIcon = newIcon;

			Manager m = getManager();
			if (m != null) {m.invalidate();}
		}
    }

    public void setDrawPosition( int drawPosition ) {_drawPosition = drawPosition;}

    public void layout(int width, int height)
    {
    	_labelHeight = VPADDING;
        _leftOffset = HPADDING;
        _rightOffset = HPADDING;

        if (_avatarIcon != null) {_leftOffset += _avatarIcon.getWidth() + HPADDING;}

        if (_labelContent != null)
        {
        	_labelContent.layout(width - _leftOffset - _rightOffset, height);
            _labelHeight += _labelContent.getHeight();	
        }

        if (_labelTime != null)
        {
        	_labelTime.layout(width- _leftOffset - _rightOffset, height);
        	_labelHeight += _labelTime.getHeight();
        }

        if (_avatarIcon != null) {_labelHeight = (_avatarIcon.getHeight() >= _labelHeight) ? _avatarIcon.getHeight() + 2 * VPADDING : _labelHeight;}

        setExtent(width, _labelHeight);
    }

    public void setAvatarIcon(byte[] data)
    {
    	if(_avatarIcon!=null && data!=null)
    	{
    		EncodedImage image=EncodedImage.createEncodedImage(data, 0, data.length);
    		_avatarIcon=image.getBitmap();
    		
    		invalidate();
    		//updateLayout();
    	}
    }

    public void setStatusImage(byte[] data)
    {
    	if(_image_Status!=null && data!=null)
    	{
    		EncodedImage image=EncodedImage.createEncodedImage(data, 0, data.length);
    		_image_Status=Function.bestFit(image, 80, 80);

    		invalidate();
    		//updateLayout();
    	}
    }

    public void setRetweetImage(byte[] data)
    {
    	if(_image_Retweet!=null && data!=null)
    	{
    		EncodedImage image=EncodedImage.createEncodedImage(data, 0, data.length);
    		_image_Retweet=Function.bestFit(image, 80, 80);
    		
    		invalidate();
    		//updateLayout();
    	}
    }
    
    protected void paint(Graphics g)
    {
    	int currentTop=VPADDING;
    	
        // Avatar Bitmap
        if(_avatarIcon != null)
        {
            g.drawBitmap(HPADDING, currentTop, _avatarIcon.getWidth(), _avatarIcon.getHeight(), _avatarIcon, 0, 0);
        }
        
        // Screen name Text
        try {
            g.pushRegion(_leftOffset, currentTop, getWidth() - _leftOffset - _rightOffset, _labelContent.getHeight(), 0, 0);
            _labelContent.paint(g);
        } finally {g.popContext();}
        
        // Time Text
        if(_labelTime !=null)
        {
        	try {
        		g.setColor(Color.DARKGRAY);
    			g.setFont(FONT_TIME);
        		g.pushRegion(_leftOffset, getHeight() - _labelTime.getHeight(), _labelTime.getWidth(), _labelTime.getHeight(),0,0);
        		_labelTime.paint(g);
        	} finally{g.popContext();}
        }
    }

    protected void paintBackground(Graphics g)
    {
        if(_drawPosition < 0)
        {
            super.paintBackground(g);
            return;
        }

        int oldColour = g.getColor();
        
        int background = g.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS) ? COLOR_BACKGROUND_FOCUS : COLOR_BACKGROUND;
        
        try {
            if(_drawPosition == 0)
            {
                // Top
                g.setColor(background);
                g.fillRoundRect(0, 0, getWidth(), getHeight() + CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS);
                g.setColor(COLOR_BORDER);
                g.drawRoundRect(0, 0, getWidth(), getHeight() + CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS);
                g.drawLine(0, getHeight() - 1, getWidth(), getHeight() - 1);
            } else if(_drawPosition == 1) {
                // Bottom 
                g.setColor(background);
                g.fillRoundRect(0, -CORNER_RADIUS, getWidth(), getHeight() + CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS);
                g.setColor(COLOR_BORDER);
                g.drawRoundRect(0, -CORNER_RADIUS, getWidth(), getHeight() + CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS);
            } else if(_drawPosition == 2) {
                // Middle
                g.setColor(background);
                g.fillRoundRect(0, -CORNER_RADIUS, getWidth(), getHeight() + 2 * CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS);
                g.setColor(COLOR_BORDER);
                g.drawRoundRect(0, -CORNER_RADIUS, getWidth(), getHeight() + 2 * CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS);
                g.drawLine(0, getHeight() - 1, getWidth(), getHeight() - 1);
            } else {
                // Single
                g.setColor(background);
                g.fillRoundRect(0, 0, getWidth(), getHeight(), CORNER_RADIUS, CORNER_RADIUS);
                g.setColor(COLOR_BORDER);
                g.drawRoundRect(0, 0, getWidth(), getHeight(), CORNER_RADIUS, CORNER_RADIUS);
            }
        } finally {
            g.setColor(oldColour);
        }
    }
    
    protected void drawFocus(Graphics g, boolean on)
    {
        if(_drawPosition < 0)
        {
            super.drawFocus(g, on);
        } else {
            boolean oldDrawStyleFocus = g.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS);
            
            try {
                if(on)
                {
                	g.setColor(Color.WHITE);
                    g.setDrawingStyle(Graphics.DRAWSTYLE_FOCUS, true);
                }
                
                paintBackground(g);
                paint(g);
            } finally {
                g.setDrawingStyle(Graphics.DRAWSTYLE_FOCUS, oldDrawStyleFocus);
            }
        }
    }
    
    protected boolean keyChar(char character, int status, int time) 
    {
        if(character == Characters.ENTER)
        {
            clickButton();
            return true;
        }
        
        return super.keyChar(character, status, time);
    }
    
    protected boolean navigationClick(int status, int time) 
    {
        clickButton(); 
        return true;    
    }
    
    protected boolean trackwheelClick(int status, int time)
    {        
        clickButton();    
        return true;
    }
    
    protected boolean invokeAction(int action) 
    {
        switch(action)
        {
            case ACTION_INVOKE:
                clickButton(); 
                return true;
        }
        
        return super.invokeAction(action);
    }

    public void clickButton() {fieldChangeNotify(0);}
       
    protected boolean touchEvent(TouchEvent message)
    {
        int x = message.getX(1);
        int y = message.getY(1);
        
        if(x < 0 || y < 0 || x > getExtent().width || y > getExtent().height) {return false;}
        
        switch(message.getEvent())
        {
        	case TouchEvent.CLICK:
                clickButton();
                return true;
        }
        
        return super.touchEvent(message);
    }

    public void setDirty( boolean dirty ) {}
    public void setMuddy( boolean muddy ) {}
}